#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import time
import socket
# import RPi.GPIO as GPIO
# from PCA9685 import PCA9685


# channel 0, camera up/down
# on = 100, off: 210 - 490, middle = 400

# channel 1, camera left/right
# on = 100, off: 220 - 650, middle = 400

# channel 2, direction left/right
# on = 100, off: 240 - 500, middle = 400


TCP_RX_SIZE_MAX = (10 * 1024)


# class Servo(object):
# 	"""docstring for Servo"""
# 	def __init__(self, pwmHdl, delay, channel, step, deadZone, minPwm, maxPwm, initPwm):
# 		super(Servo, self).__init__()
# 		self.hdl = pwmHdl
# 		self.delay = delay
# 		self.channel = channel
# 		self.step = step
# 		self.deadZone = deadZone
# 		self.minPwm = minPwm
# 		self.maxPwm = maxPwm
# 		self.pwm = initPwm
# 		self.SetPwm(self.pwm)

# 	def SetPwm(self, pwm):
# 		time.sleep(self.delay)
# 		self.hdl.setPWM(self.channel, self.deadZone, self.deadZone + pwm)
# 		return self.pwm


# 	def SetAngle(self, angle):
# 		if angle < 0 or angle > 180:
# 			return self.pwm
# 		targetPwm = int((angle * (2000 / 180) + 500) * 4096 / 20000)
# 		print("angle %d target pwm %d cur pwm %d" % (angle, targetPwm, self.pwm))
# 		if targetPwm >= self.minPwm and targetPwm <= self.maxPwm:
# 			self.pwm = targetPwm
# 			self.SetPwm(self.pwm)
# 		return self.pwm


# 	def IncreasePwm(self):
# 		targetPwm = self.pwm + self.step
# 		if targetPwm > self.maxPwm:
# 			targetPwm = self.maxPwm
# 		print("target pwm %d cur pwm %d" % (targetPwm, self.pwm))
# 		if self.pwm != targetPwm:
# 			self.pwm = targetPwm
# 			self.SetPwm(self.pwm)
# 		return self.pwm


# 	def DecreasePwm(self):
# 		targetPwm = self.pwm - self.step
# 		if targetPwm < self.minPwm:
# 			targetPwm = self.minPwm
# 		print("target pwm %d cur pwm %d" % (targetPwm, self.pwm))
# 		if self.pwm != targetPwm:
# 			self.pwm = targetPwm
# 			self.SetPwm(self.pwm)
# 		return self.pwm


# class DCMotor(object):
# 	"""docstring for DCMotor"""

# 	STATE_STOP		= 0
# 	STATE_FORWARD 	= 1
# 	STATE_BACKWARD	= 2


# 	def __init__(self, pwmHdl, delay, chanForward, chanBackward, deadZone, minPwm, maxPwm):
# 		super(DCMotor, self).__init__()
# 		self.hdl = pwmHdl
# 		self.delay = delay
# 		self.chanForward = chanForward
# 		self.chanBackward = chanBackward
# 		self.deadZone = deadZone
# 		self.minPwm = minPwm
# 		self.maxPwm = maxPwm
# 		self.runState = self.STATE_STOP
# 		self.Stop()


# 	def Stop(self):
# 		if self.runState == self.STATE_BACKWARD:
# 			self.hdl.SetPwmFull(self.chanBackward, False)
# 			self.hdl.SetPwmFull(self.chanForward, False)
# 		else:
# 			self.hdl.SetPwmFull(self.chanForward, False)
# 			self.hdl.SetPwmFull(self.chanBackward, False)

# 		self.runState = self.STATE_STOP


# 	def Run(self, direction, pwm):
# 		if direction == self.STATE_FORWARD:
# 			operChan = self.chanForward
# 		elif direction == self.STATE_BACKWARD:
# 			operChan = self.chanBackward
# 		else:
# 			return

# 		if pwm < self.minPwm or pwm > self.maxPwm:
# 			return

# 		# 如果前后方向发生变化，则应先停止，后配置，防止过电流
# 		if self.runState != direction:
# 			self.hdl.SetPwmFull(self.chanBackward, False)
# 			self.hdl.SetPwmFull(self.chanForward, False)
# 			self.runState = direction
# 			time.sleep(self.delay)

# 		self.hdl.setPWM(operChan, self.deadZone, self.deadZone + pwm)


# 	def FullSpeed(self, direction):
# 		if direction == self.STATE_FORWARD:
# 			operChan = self.chanForward
# 		elif direction == self.STATE_BACKWARD:
# 			operChan = self.chanBackward
# 		else:
# 			return

# 		# 如果前后方向发生变化，则应先停止，后配置，防止过电流
# 		if self.runState != direction:
# 			self.hdl.SetPwmFull(self.chanBackward, False)
# 			self.hdl.SetPwmFull(self.chanForward, False)
# 			self.runState = direction
# 			time.sleep(self.delay)

# 		self.hdl.SetPwmFull(operChan, True)


def ParseProcess(data):
	print(data)


try:
	# channel = int(sys.argv[1])
	# on  = int(sys.argv[2])
	# off = int(sys.argv[3])
	# print("set on %d off %d" % (on, off));

	# 方向舵机路数编号
	# chanDir = 0

	# GPIO.setmode(GPIO.BCM)

	# pwm = PCA9685(address=0x40, oe=4, debug=False)
	# pwm.setPWMFreq(50)

	# 创建方向舵机
	# servo = Servo(pwmHdl=pwm, delay=0.01, channel=chanDir, step=2, \
	# 			deadZone=128, minPwm=110, maxPwm=390, initPwm=300)

	# 创建动力电机，启动默认停止状态
	# dcMotor = DCMotor(pwmHdl=pwm, delay=0.1, chanForward=2, chanBackward=3, \
	# 				deadZone=16, minPwm=1024, maxPwm=4095)

	# 创建TCP监听指令
	host = "localhost"
	# host = "127.0.0.1"
	port = 11223

	sockSvr = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sockSvr.settimeout(60)
	sockSvr.bind((host, port))
	sockSvr.listen(1)

	while True:
		client, addr = sockSvr.accept()
		print(addr, "connected")

		while True:
			data = client.recv(TCP_RX_SIZE_MAX)
			if not data:
				print(addr, "disconnected")
				break

			localTime = time.asctime( time.localtime(time.time()))
			print(localTime,' recv %d:' % len(data), data.decode())

			ParseProcess(data)


	# while True:
	# 	dcMotor.Stop()
	# 	time.sleep(1)

	# 	dcMotor.Run(dcMotor.STATE_FORWARD, 1024)
	# 	time.sleep(1)

	# 	dcMotor.Run(dcMotor.STATE_FORWARD, 2048)
	# 	time.sleep(1)

	# 	dcMotor.FullSpeed(dcMotor.STATE_FORWARD)
	# 	time.sleep(1)

	# 	dcMotor.Run(dcMotor.STATE_BACKWARD, 1024)
	# 	time.sleep(1)

	# 	for i in range(100, 400, 1):
	# 		servo.IncreasePwm()
	# 	for i in range(400, 100, -1):
	# 		servo.DecreasePwm()


except Exception as e:
	raise e
finally:
	sockSvr.close()
	pwm.CleanUp()
	GPIO.cleanup()
